import router from '@/router'
import store from '@/store'
import axios from 'axios'
import { Message } from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})
// 请求拦截器
service.interceptors.request.use(config => {
// Do something before request is sent
// 携带token
  const token = store.getters.token
  // 判断是否携带
  if (token) {
    config.headers.Authorization = 'Bearer ' + token
  }
  return config
}, error => {
// Do something with request error
  return Promise.reject(error)
})
// 响应拦截器
service.interceptors.response.use(response => {
// Do something before response is sent
// 解构
  const { data } = response
  // 判断是否是失败
  if (!data.success) {
    // 返沪i错误的Promise对象
    Message.error(data.message)
    return Promise.reject(new Error(data.message))
  }
  return data
}, error => {
// Do something with response error
// 判断401  多层解构
  const { response: { status, data: { code }}} = error
  // 判断响应状态码和业务状态码
  if (status === 401 && code === 10002) {
    // 调用退出的方法  删除token等
    store.commit('user/logout')
    // 跳转  然后传入当前的路由  再次登录直接回到此页面
    router.push(`/login?redirect=${router.currentRoute.fullPath}`)
  }
  Message.error(error.message)
  return Promise.reject(error)
})
export default service
